<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href>商品管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>更新商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card v-loading="loading">
      <!-- 提示区域 -->
      <el-alert title="更新商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="手工设置"></el-step>
        <el-step title="优惠券设置"></el-step>
        <el-step title="商品活动"></el-step>
        <el-step title="展示版块"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品详情"></el-step>
        <el-step title="备注信息"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- tab栏区域 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称:" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格:" prop="price">
              <el-input v-model="addForm.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量:" prop="weight">
              <el-input v-model="addForm.weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量:" prop="number">
              <el-input v-model="addForm.number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品库存:" prop="stock">
              <el-input v-model="addForm.stock" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类:" prop="category">
              <el-select v-model="addForm.category" placeholder="请选择商品分类" @change="cat">
                <el-option
                  v-for="item in categoryList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="手工设置" name="1">
            <el-form-item label="手工项目:">
              <!-- 作用域插槽 -->
              <template slot-scope>
                <el-switch v-model="addForm.handwork"></el-switch>
              </template>
            </el-form-item>
            <el-form-item label="包含手工次数:">
              <el-input v-model="addForm.handworkNum" type="number"></el-input>
            </el-form-item>
            <el-form-item label="有效期(天):">
              <!-- <el-input v-model="addForm.termOfValidity" type="number"></el-input> -->
              <el-select v-model="addForm.termOfValidity" placeholder="请选择过期的天数">
                <el-option
                  v-for="item in termOfValidityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="优惠券设置" name="2">
            <el-form-item label="是否可使用优惠券:" label-width="150px">
              <!-- 作用域插槽 -->
              <template slot-scope>
                <el-switch v-model="addForm.coupon"></el-switch>
              </template>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品活动" name="3">
            <el-form-item v-model="addForm.activityItem">
              <el-checkbox-group v-model="addForm.activityItem">
                <el-checkbox v-for="(item,i) in activityItemList" :label="item" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="展示版块" name="4">
            <el-form-item v-model="addForm.displayPage">
              <el-checkbox-group v-model="addForm.displayPage">
                <el-checkbox v-for="(item,i) in displayPageList" :label="item" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="5">
            <!-- action 表示上传图片地址，后台api接口 -->
            <el-upload
              action="http://localhost:3000/api/uploadGoodsMainPic"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="6">
            <!-- 上传商品详情图片 -->
            <el-upload
              action="http://localhost:3000/api/uploadGoodsDetailsPic"
              :on-preview="handlePreview"
              :on-remove="handleRemoveTwo"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccessTwo"
              :file-list="detailsFileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="备注信息" name="7">
            <el-form-item label="备注:">
              <el-input v-model="addForm.remarks"></el-input>
            </el-form-item>
            <el-button size="small" type="primary" @click="updateGoods">更新商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
import {
  getCategoryList,
  getOtherInfo,
  delGoodsImg,
  convertPath
} from '../../api/goods/add.js'
import { getGoodsById, updateGoodsById, timeStampToDays } from '../../api/goods/update.js'
export default {
  data() {
    return {
      loading: false,
      activeIndex: '0',
      //   图片预览图片路径名称
      previewPath: '',
      //   图片预览框显示 与 关闭
      previewVisible: false,
      //   添加商品的表单数据对象
      addForm: {
        name: '',
        price: 0,
        weight: 0,
        number: 0,
        stock: 0,
        category: '',
        // 商品添加到活动项目
        activityItem: [],
        // 商品需要展示的版块
        displayPage: [],
        //  上传成功的图片加入到此数组里
        imgs: [],
        // 上传成功的商品详情图片加入到此数组里
        details_imgs: [],
        main_img: '',
        // 手工商品
        handwork: false,
        // 手工数量
        handworkNum: 0,
        coupon: false,
        // 是否包邮
        free_shipping: false,
        // 手工商品有效期
        termOfValidity: 0,
        // 创建时间
        createTime: 0,
        // 备注
        remarks: '',
        // 是否上架
        upper_shelf: false
      },
      categoryList: [],
      activityItemList: [],
      displayPageList: [],
      cities: [],
      //   已上传的商品图片组
      fileList: [],
      //   已上传的商品详情图片组
      detailsFileList: [],
      // 有效期选项
      termOfValidityOptions: [
        {
          value: '5',
          label: '五天'
        },
        {
          value: '10',
          label: '十天'
        },
        {
          value: '30',
          label: '一个月'
        },
        {
          value: '60',
          label: '两个月'
        },
        {
          value: '90',
          label: '三个月'
        },
        {
          value: '180',
          label: '六个月'
        },
        {
          value: '365',
          label: '一年'
        },
        {
          value: '730',
          label: '两年'
        },
        {
          value: '1095',
          label: '三年'
        }
      ],
      //   图片上传组件的headers请求头对象（里面可以包含Token）
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //   表单验证规则
      addFormRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        stock: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        category: [
          { required: true, message: '请输入选择商品分类', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getGoods(this.$route.query.id)
    this.getcategory()
  },
  methods: {
    // 按id查询商品信息
    getGoods(id) {
      console.log('接收id:' + id)
      getGoodsById(id).then(res => {
        console.log(res.data)
        if (Object.keys(res.data.data).length > 0) {
          this.addForm = res.data.data
          this.fileList = res.data.goodsImgsUrl
          this.detailsFileList = res.data.goodsDetailsImgsUrl
        }
        console.log(this.addForm)
      })
    },
    getcategory() {
      getCategoryList().then(res => {
        console.log(res.data)
        if (!res.data.success) return this.$message.error('获取商品分类列表失败')
        this.categoryList = res.data.data
      })
    },
    getOther() {
      getOtherInfo().then(res => {
        console.log(res.data)
        if (!res.data.success) return this.$message.error('获取商品活动信息失败')
        // 绑定商品活动设置
        if (res.data.data.length > 0) {
          this.activityItemList = res.data.data[0].activityItem
        }
        console.log(this.activityItemList)
        // 绑定商品展示设置
        if (res.data.data.length > 0) {
          this.displayPageList = res.data.data[0].displayPage
        }
        console.log(this.displayPageList)
      })
    },
    cat() {
      console.log(this.addForm)
    },
    beforeTabLeave(activeName, oldActiveName) {
      console.log(activeName, oldActiveName)
      if (oldActiveName === '0' && !this.addForm.category) {
        this.$message.error('还未选择商品分类')
        return false
      } else {
      }
    },
    tabClicked() {
      console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        this.getOther()
        console.log('第二个项目')
        console.log(this.addForm.termOfValidity)
        timeStampToDays(this.addForm.createTime, this.addForm.termOfValidity).then(res => {
          console.log(parseInt(res))
          if (res > 0) {
            for (let i = 0; i < this.termOfValidityOptions.length; i++) {
              if (Number(this.termOfValidityOptions[i].value) === parseInt(res)) {
                this.addForm.termOfValidity = this.termOfValidityOptions[i].value
              }
            }
            // console.log(this.addForm)
          }
        })
      } else if (this.activeIndex === '2') {
        console.log(this.addForm)
      } else if (this.activeIndex === '3') {
        console.log(this.addForm)
      }
    },
    // 处理图片预览功能
    handlePreview(file) {
      console.log(file)
      //   得到云服务器上的文件路径
      const path = file.response.data.file_id
      //   将云数据 cloud: 转换成 http: 路径
      this.loading = true
      this.previewPath = ''
      convertPath(path).then(res => {
        console.log(res.data)
        this.loading = false
        if (!res.data.success) {
          return this.$message.error('图片打开失败')
        }

        if (res.data.data.length > 0) {
          this.previewPath = res.data.data[0].url
        }
        console.log(this.previewPath)
        this.previewVisible = true
      })
    },
    // 处理商品图片移除的功能
    handleRemove(file) {
      console.log(file)
      //   判断从新上传取得的还是从数组导入的
      console.log(!file.response)
      if (!file.response) {
        console.log('进入数组导入的图片')
        // 从数组导入的图片路径
        //   1.获取上传文件临时路径
        const filePaht = file.fileid
        console.log(filePaht)
        //   2.从数组中找到这个图片的对应的索引值 i
        const i = this.addForm.imgs.findIndex(x => x === filePaht)
        console.log('查到位置索引：' + i)
        //   3.得到索引值后，从数组里把这个上传文件的临时路径删除掉
        this.addForm.imgs.splice(i, 1)
        console.log(this.addForm)
        // 4.再删除导入数组图片的路
        const n = this.fileList.findIndex(x => x.fileid === filePaht)
        console.log('查询数组索引位置:' + n)
        this.fileList.splice(n, 1)
        console.log(this.fileList)
        // 5.删除云数据库里的图片文件
        delGoodsImg(filePaht).then(res => {
          console.log(res.data)
          if (res.data.data.errmsg === 'ok') {
            this.$message.success('图片删除成功')
          }
        })
      } else {
        console.log('进入新上传的图片')
        //  新上传的图片路径
        //   1.获取上传文件临时路径
        const filePaht = file.response.data.file_id
        console.log(filePaht)
        //   2.从数组中找到这个图片的对应的索引值 i
        const i = this.addForm.imgs.findIndex(x => x === filePaht)
        console.log('得到索引位置' + i)
        //   3.得到索引值后，从数组里把这个上传文件的临时路径删除掉
        this.addForm.imgs.splice(i, 1)
        console.log(this.addForm)
        // 4.删除云数据库里的图片文件
        delGoodsImg(filePaht).then(res => {
          console.log(res.data)
          if (res.data.data.errmsg === 'ok') {
            this.$message.success('图片删除成功')
          }
        })
      }
    },
    // 处理商品详情图片移除功能
    handleRemoveTwo(file) {
      console.log('Two')
      console.log(file)
      //   判断从新上传取得的还是从数组导入的
      if (!file.response) {
        // 从数组导入的图片路径
        //   1.获取上传文件临时路径
        const filePaht = file.fileid
        console.log(filePaht)
        // console.log(this.fileList)
        //   2.从数组中找到这个图片的对应的索引值 i
        const i = this.addForm.details_imgs.findIndex(x => x === filePaht)
        //   3.得到索引值后，从数组里把这个上传文件的临时路径删除掉
        this.addForm.details_imgs.splice(i, 1)
        // 4.再删除导入数组图片的路
        const n = this.detailsFileList.findIndex(x => x.fileid === filePaht)
        this.detailsFileList.splice(n, 1)
        console.log(this.addForm)
        console.log(this.detailsFileList)
        // 5.删除云数据库里的图片文件
        delGoodsImg(filePaht).then(res => {
          console.log(res.data)
          if (res.data.data.errmsg === 'ok') {
            this.$message.success('图片删除成功')
          }
        })
      } else {
        //  新上传的图片路径
        //   1.获取上传文件临时路径
        const filePaht = file.response.data.file_id
        console.log(filePaht)
        //   2.从数组中找到这个图片的对应的索引值 i
        const i = this.addForm.details_imgs.findIndex(x => x === filePaht)
        //   3.得到索引值后，从数组里把这个上传文件的临时路径删除掉
        this.addForm.details_imgs.splice(i, 1)
        console.log(this.addForm)
        // 4.删除云数据库里的图片文件
        delGoodsImg(filePaht).then(res => {
          console.log(res.data)
          if (res.data.data.errmsg === 'ok') {
            this.$message.success('图片删除成功')
          }
        })
      }
    },
    // 监听上传商品图片成功后事件
    handleSuccess(response, file) {
      console.log(response)
      console.log(file)
      //   console.log(response.data.file_id)
      if (!response.data.file_id) return this.$message.error('图片上传失败')
      //   将上传成功的图片加入到imgs数组里
      this.addForm.imgs.push(response.data.file_id)
      this.fileList.push({
        name: file.name,
        url: file.url,
        fileid: response.data.file_id
      })
      console.log(this.addForm)
      console.log(this.fileList)
    },
    // 监听上传商品详情图片成功后事件
    handleSuccessTwo(response, file) {
      console.log(response)
      //   console.log(response.data.file_id)
      if (!response.data.file_id) return this.$message.error('图片上传失败')
      //   将上传成功的图片加入到imgs数组里
      this.addForm.details_imgs.push(response.data.file_id)
      this.detailsFileList.push({
        name: file.name,
        url: file.url,
        fileid: response.data.file_id
      })
      console.log(this.addForm)
      console.log(this.detailsFileList)
    },
    // 更新商品
    updateGoods() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
        // 检查商品商品是否包含一张图片，如果商品图片数组等于0，提示需要上传一张商品图片
        if (this.addForm.imgs.length <= 0) {
          return this.$message.error('请上传商品图片！')
        }
        // 检查商品详情图片是否包含一张图片，如果商品详情图片数组等于0，提示需要上传一张商品图片
        if (this.addForm.details_imgs.length <= 0) {
          return this.$message.error('请上传商品详情图片！')
        }
        console.log(this.addForm)
        //  执行添加
        updateGoodsById(this.addForm).then(res => {
          console.log(res.data)
          if (res.data.success) {
            this.$message.success('商品更新成功')
            this.$router.push('/goods')
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important ;
}
.previewImg {
  width: 100%;
}
</style>
